package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.TableNameConstant;
import cc.rengu.igas.bomp.common.dao.*;
import cc.rengu.igas.bomp.common.dao.impl.*;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.*;
import cc.rengu.igas.bomp.common.util.ChangeNextStatusUtil;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.realize.MchntVerifyService;
import cc.rengu.igas.bomp.core.realize.impl.MchntVerifyServiceImpl;
import cc.rengu.igas.bomp.core.service.base.AuditService;
import cc.rengu.igas.bomp.facade.bean.CashWithdrawalFeeInfoBean;
import cc.rengu.igas.bomp.facade.enums.BompSettleTypeEnum;
import cc.rengu.igas.bomp.facade.request.MchntWithdrawManageRequest;
import cc.rengu.igas.bomp.facade.response.MchntWithdrawManageResponse;
import cc.rengu.igas.share.common.enums.SettleAcctTypeEnum;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: zhangxuran
 * @Date: 2020/4/28 14:56
 * @Description: 提现费率管理
 */
public class MchntWithdrawManageService extends AuditService {

    /* 基础产品 */
    private static String BASE_PROD_TYPE = "*";

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntWithdrawManageRequest request = new MchntWithdrawManageRequest();
        ConvertUtil.convertOutput(request);
        return request;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntWithdrawManageRequest mchntWithdrawManageRequest = (MchntWithdrawManageRequest) request;
        CashWithdrawalFeeInfoBean cashWithdrawalFeeInfoBean = mchntWithdrawManageRequest.getCashWithdrawalFeeInfoBean();
        MchntWithdrawManageResponse mchntWithdrawManageResponse = new MchntWithdrawManageResponse();
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        String time = DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS);

        String instId = mchntWithdrawManageRequest.getHeader().getInstId();
        String mchntNo = mchntWithdrawManageRequest.getMchntNo();

        //设置提现费率
        if ("1".equals(mchntWithdrawManageRequest.getOprType())) {

            BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
            List<BizTmp> tmpList = bizTmpMapper.selectBizTmpListByMchntNo(instId, mchntNo);
            if (!CollectionUtils.isEmpty(tmpList)) {
                Optional<BizTmp> matchOptional = tmpList.stream().filter(item -> ChangeNextStatusUtil.isAllowModifyDataByAuditAndTable(item.getAuditStatus(), item.getOprTableEname())).findFirst();
                if (matchOptional.isPresent()) {
                    rglog.error("提现费率管理失败！数据库中有数据待审核！传入instId:{},表名:{}."
                            , instId, matchOptional.get().getOprTableEname());
                    throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(),
                            RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
                }

                matchOptional = tmpList.stream().filter(item -> AuditStatusEnum.MODIFY_BE_COMMIT_AUDIT.getAuditStatus().equals(item.getAuditStatus())).findFirst();
                if (matchOptional.isPresent()) {
                    rglog.error("提现费率管理失败！数据库中有修改草稿！传入instId:{},表名:{}."
                            , instId, matchOptional.get().getOprTableEname());
                    throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(),
                            RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
                }
            }


            String auditStatus = AuditStatusEnum.MODIFY_BE_AUDIT.getAuditStatus();
            String updateTime = DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS);
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            MchntBaseInfo dbMchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
            //判断商户是否允许修改
            if (null == dbMchntBaseInfo
                    || (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(dbMchntBaseInfo.getMchntType()) && AppParamConstant.NO.equals(dbMchntBaseInfo.getIndependentDataFlag()))) {
                rglog.error("提现管理失败, 当前商户信息为空，或商户为连锁商户门店非独立维护不允许设置提现，instId:{},mchntNo:{}",
                        instId, mchntNo);
                throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
            }

            //特殊费率不允许开通提现
            MchntFeeInfoMapper mchntFeeInfoMapper = new MchntFeeInfoMapperImpl();
            List<MchntFeeInfo> mchntFeeInfoList = mchntFeeInfoMapper.selectMchntFeeInfoByMchntNo(instId, mchntNo);
            if (!CollectionUtils.isEmpty(mchntFeeInfoList)) {
                mchntFeeInfoList = mchntFeeInfoList.stream().filter(item -> "0".equals(item.getFeeInputMode()) && !StringUtil.isEmptyOrNull(item.getFeeCode())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(mchntFeeInfoList)) {
                    for (MchntFeeInfo mchntFeeInfo : mchntFeeInfoList) {
                        if ("0".equals(mchntFeeInfo.getFeeInputMode())
                                && !StringUtil.isEmptyOrNull(mchntFeeInfo.getFeeCode())) {
                            //特殊费率，且在当前日期生效
                            if (DateUtil.compareDate(DateUtil.getCurrentDate(), mchntFeeInfo.getFeeEffectiveDate()) >= 0
                                    && DateUtil.compareDate(DateUtil.getCurrentDate(), mchntFeeInfo.getFeeExpiryDate()) <= 0) {
                                rglog.error("提现管理失败, 商户使用特殊费率不允许开通提现，instId:{},mchntNo:{}。",
                                        dbMchntBaseInfo.getInstId(), dbMchntBaseInfo.getMchntNo());
                                throw new BizException(RespCodeEnum.NOT_ALLOW_TO_SET_WITHDRAWAL_OF_FEE.getRespCode(), RespCodeEnum.NOT_ALLOW_TO_SET_WITHDRAWAL_OF_FEE.getRespDesc());
                            }
                        }
                    }
                }
            }

            //校验是否允许进行提现
            MchntVerifyService mchntVerifyService = new MchntVerifyServiceImpl();
            if (!mchntVerifyService.verifyMchntAllowToWithdrawal(dbMchntBaseInfo)) {
                rglog.error("该商户未达到提现要求，不允许设置提现费率！instId:{}, mchntNo:{}", dbMchntBaseInfo.getInstId(), dbMchntBaseInfo.getMchntNo());
                throw new BizException(RespCodeEnum.NOT_ALLOW_WITHDRAWAL_OF_CONDITION.getRespCode(), RespCodeEnum.NOT_ALLOW_WITHDRAWAL_OF_CONDITION.getRespDesc());
            }

            MchntAcctInfoMapper mchntAcctInfoMapper = new MchntAcctInfoMapperImpl();
            MchntAcctInfo mchntAcctInfo = mchntAcctInfoMapper.selectMchntAcctInfoByPrimaryKey(instId, mchntNo, "*", FundTypeEnum.SETTLE_TYPE.getFundCode());
            if (BompSettleTypeEnum.SETTLE_TYPE_D0.getType().equals(mchntAcctInfo.getSettleType())) {
                //不允许开通提现
                rglog.error("结算账户为D0结算，不允许开通提现");
                throw new BizException(RespCodeEnum.NOT_TO_ALLOW_WITHDRAWAL_AND_DO.getRespCode(), RespCodeEnum.NOT_TO_ALLOW_WITHDRAWAL_AND_DO.getRespDesc());
            }

            /* 获取机构内部户 提现/D0（本行）： 垫资户  */
            SettleAcctTypeEnum settleAcctTypeEnum = SettleAcctTypeEnum.DZ_SUBJECT;
            RoleAcctInfoMapper roleAcctInfoMapper = new RoleAcctInfoMapperImpl();
            RoleAcctInfo roleAcctInfo = roleAcctInfoMapper.selectBompBankRoleAcctInfoBySettleAcctId(dbMchntBaseInfo.getInstId(), settleAcctTypeEnum.getSettleAcct());
            if (null == roleAcctInfo) {
                rglog.error("查询法人行垫资户失败，不允许设置D0与提现！userId:<{}>，mchntNo:<{}>", mchntWithdrawManageRequest.getUserId(), dbMchntBaseInfo.getMchntNo());
                throw new BizException(RespCodeEnum.NOT_ALLOW_D0_WITHDRAWAL.getRespCode(), RespCodeEnum.NOT_ALLOW_D0_WITHDRAWAL.getRespDesc());
            }

            List<BizTmp> bizTmpList = new ArrayList<>();

            /* 修改商户基本信息 */
            MchntBaseInfo modifyBaseInfo = new MchntBaseInfo();
            BeanUtil.beanCopy(dbMchntBaseInfo, modifyBaseInfo);

            //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
            BizTmp baseBizTmp = bizTmpMapper.selectBizTmpByRealId(dbMchntBaseInfo.getInstId(), dbMchntBaseInfo.getId());
            if (null == baseBizTmp) {
                baseBizTmp = new BizTmp();
                ConvertUtil.convertOutput(baseBizTmp);
                baseBizTmp.setMchntName(dbMchntBaseInfo.getMchntName());
                baseBizTmp.setManageInstId(dbMchntBaseInfo.getSignInstId());
                baseBizTmp.setRealId(dbMchntBaseInfo.getId());
                baseBizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_BASE_INFO);
                baseBizTmp.setMasterShowFlag(BompAppParamConstant.FLAG_Y);
                baseBizTmp.setDetailFlag(BompAppParamConstant.FLAG_N);
                baseBizTmp.setMasterKey(dbMchntBaseInfo.getId());
            } else if (AuditStatusEnum.MODIFY_BE_COMMIT_AUDIT.getAuditStatus().equals(dbMchntBaseInfo.getAuditStatus())) {
                //若当前状态为修改待提交，则取临时表中的数据进行修改   (例如，在商户基本管理页面进行了修改，此时临时表中存的是修改后的数据，此时进行结算账户修改，修改结算模式，则需从临时表中取数据，进行修改再存放到临时表中)
                String tmpBaseInfoJson = InitParamUtil.getJsonString(baseBizTmp);
                MchntBaseInfo tmpBaseInfo = JSON.parseObject(tmpBaseInfoJson, MchntBaseInfo.class);
                BeanUtil.beanCopy(tmpBaseInfo, modifyBaseInfo);
            }


            modifyBaseInfo.setCashWithdrawalFlag(BompAppParamConstant.FLAG_Y);
            modifyBaseInfo.setAuditStatus(auditStatus);
            modifyBaseInfo.setLastOprId(mchntWithdrawManageRequest.getUserId());

            dbMchntBaseInfo.setAuditStatus(auditStatus);
            dbMchntBaseInfo.setLastOprId(mchntWithdrawManageRequest.getUserId());
            dbMchntBaseInfo.setLastUpdateTime(updateTime);

            //修改
            baseBizTmp.setBizOpr("U");
            baseBizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
            //修改待提交审批
            baseBizTmp.setAuditStatus(auditStatus);
            String modifyMchntBaseInfoJson = JSONObject.toJSONString(modifyBaseInfo);
            InitParamUtil.initBizTempData(baseBizTmp, modifyMchntBaseInfoJson);
            bizTmpList.add(baseBizTmp);

            String date = DateUtil.getCurrentDate();
            MchntFeeInfo dbMchntFeeInfo = mchntFeeInfoMapper.selectMchntFeeInfoByCondition(instId, mchntNo, cashWithdrawalFeeInfoBean.getBaseProdCode(), cashWithdrawalFeeInfoBean.getFeeType(), date);
            if (null == dbMchntFeeInfo) {
                //开通提现
                MchntFeeInfo newFeeInfo = InitParamUtil.initMchntFeeInfoByCreateCastWithdraw(cashWithdrawalFeeInfoBean, dbMchntBaseInfo, auditStatus, time, mchntWithdrawManageRequest.getUserId());
                BizTmp feeBizTmp = InitParamUtil.initBizTmpByCreate(dbMchntBaseInfo, newFeeInfo.getId(),
                        JSONObject.toJSONString(newFeeInfo), TableNameConstant.T_B_MCHNT_FEE_INFO, auditStatus,
                        BompAppParamConstant.FLAG_N, BompAppParamConstant.FLAG_N);

                bizTmpList.add(feeBizTmp);

                //修改签约信息 -> 修改待审核
                MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
                MchntSignInfo dbMchntSignInfo = mchntSignInfoMapper.selectMchntSignInfoByPrimaryKey(instId, dbMchntBaseInfo.getMchntNo());
                if (!ChangeNextStatusUtil.isAllowModifyData(dbMchntSignInfo.getAuditStatus())) {
                    rglog.error("提现费率管理,该商户签约信息不允许修改！，instId:{},mchntNo:{},audisStatus:{}",
                            dbMchntSignInfo.getInstId(), dbMchntSignInfo.getMchntNo(), dbMchntSignInfo.getAuditStatus());
                    throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
                }
                dbMchntSignInfo.setAuditStatus(auditStatus);
                dbMchntSignInfo.setLastOprId(dbMchntBaseInfo.getLastOprId());
                dbMchntSignInfo.setLastUpdateTime(dbMchntBaseInfo.getLastUpdateTime());
                BizTmp bizTmpMchntSign = bizTmpMapper.selectBizTmpByRealId(instId, dbMchntSignInfo.getId());
                bizTmpMchntSign.setAuditStatus(auditStatus);
                bizTmpMchntSign.setLastOprId(dbMchntBaseInfo.getLastOprId());
                bizTmpMchntSign.setLastUpdateTime(dbMchntBaseInfo.getLastUpdateTime());
                InitParamUtil.initBizTempData(bizTmpMchntSign, JSONObject.toJSONString(dbMchntSignInfo));
                bizTmpList.add(bizTmpMchntSign);

                /* 将数据修改为 修改待审核 */
                createMchntCashFeeInfoDb(dbMchntBaseInfo, dbMchntSignInfo, newFeeInfo, bizTmpList);
            } else {
                //修改签约信息 -> 修改待审核
                MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
                MchntSignInfo dbMchntSignInfo = mchntSignInfoMapper.selectMchntSignInfoByPrimaryKey(instId, dbMchntBaseInfo.getMchntNo());
                if (!ChangeNextStatusUtil.isAllowModifyData(dbMchntSignInfo.getAuditStatus())) {
                    rglog.error("提现费率管理,该商户签约信息不允许修改！，instId:{},mchntNo:{},audisStatus:{}",
                            dbMchntSignInfo.getInstId(), dbMchntSignInfo.getMchntNo(), dbMchntSignInfo.getAuditStatus());
                    throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
                }
                dbMchntSignInfo.setAuditStatus(auditStatus);
                dbMchntSignInfo.setLastOprId(dbMchntBaseInfo.getLastOprId());
                dbMchntSignInfo.setLastUpdateTime(dbMchntBaseInfo.getLastUpdateTime());
                BizTmp bizTmpMchntSign = bizTmpMapper.selectBizTmpByRealId(instId, dbMchntSignInfo.getId());
                bizTmpMchntSign.setAuditStatus(auditStatus);
                bizTmpMchntSign.setLastOprId(dbMchntBaseInfo.getLastOprId());
                bizTmpMchntSign.setLastUpdateTime(dbMchntBaseInfo.getLastUpdateTime());
                InitParamUtil.initBizTempData(bizTmpMchntSign, JSONObject.toJSONString(dbMchntSignInfo));
                bizTmpList.add(bizTmpMchntSign);


                //修改费率信息 -> 新增待审核
                List<MchntFeeInfo> modifyFeeInfoList = new ArrayList<>();
                if (DateUtil.compareDate(dbMchntFeeInfo.getFeeExpiryDate(), DateUtil.getCurrentDate()) <= 0) {
                    rglog.error("当前修改的费率的失效日期<{}> 小于等于当前日期<{}>，不允许再次修改", dbMchntFeeInfo.getFeeExpiryDate(), DateUtil.getCurrentDate());
                    throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
                }

                dbMchntFeeInfo.setAuditStatus(auditStatus);
                dbMchntFeeInfo.setLastUpdateTime(dbMchntBaseInfo.getLastUpdateTime());
                dbMchntFeeInfo.setLastOprId(dbMchntBaseInfo.getLastOprId());
                modifyFeeInfoList.add(dbMchntFeeInfo);

                //临时表 中的正式数据改为失效 失效日期为当天
                MchntFeeInfo afterDbMchntFeeInfo = new MchntFeeInfo();
                BeanUtil.beanCopy(dbMchntFeeInfo, afterDbMchntFeeInfo);
                afterDbMchntFeeInfo.setFeeExpiryDate(DateUtil.getCurrentDate());
                BizTmp dbFeeBizTmp = initBizTmpByCreate(dbMchntBaseInfo, afterDbMchntFeeInfo.getId(), JSONObject.toJSONString(afterDbMchntFeeInfo),
                        TableNameConstant.T_B_MCHNT_FEE_INFO, auditStatus,
                        BompAppParamConstant.FLAG_N, BompAppParamConstant.FLAG_N);
                //源数据改为停用  审核通过是如果为停用，正式表数据失效日期改为当天
                dbFeeBizTmp.setBizOpr("D");
                bizTmpList.add(dbFeeBizTmp);

                //新增一条修改后的数据
                MchntFeeInfo newFeeInfo = InitParamUtil.initMchntFeeInfoByCastWithdraw(cashWithdrawalFeeInfoBean, dbMchntBaseInfo, auditStatus, time, mchntWithdrawManageRequest.getUserId());
                BizTmp newFeeBizTmp = InitParamUtil.initBizTmpByCreate(dbMchntBaseInfo, newFeeInfo.getId(),
                        JSONObject.toJSONString(newFeeInfo), TableNameConstant.T_B_MCHNT_FEE_INFO, auditStatus,
                        BompAppParamConstant.FLAG_N, BompAppParamConstant.FLAG_N);
                newFeeBizTmp.setRemark1(dbFeeBizTmp.getRealId());
                //新数据改为启用 审核通过是如果为启用，新增正式表数据生效日期改为下一天
                newFeeBizTmp.setBizOpr("E");
                bizTmpList.add(newFeeBizTmp);
                modifyMchntCashFeeInfoDb(dbMchntBaseInfo, dbMchntSignInfo, modifyFeeInfoList, bizTmpList);
            }


        } else {
            //查询费率信息
            String date = DateUtil.getCurrentDate();
            MchntFeeInfoMapper mchntFeeInfoMapper = new MchntFeeInfoMapperImpl();
            MchntFeeInfo dbMchntFeeInfo = mchntFeeInfoMapper.selectMchntFeeInfoByCondition(instId, mchntNo, cashWithdrawalFeeInfoBean.getBaseProdCode(), cashWithdrawalFeeInfoBean.getFeeType(), date);
            CashWithdrawalFeeInfoBean queryBean = new CashWithdrawalFeeInfoBean();
            if (null == dbMchntFeeInfo) {
                //若查询商户提现费率为空，则查询系统参数表设置的默认费率
                SysParamMapper sysParamMapper = new SysParamMapperImpl();
                SysParam sysParam = sysParamMapper.selectSysParamByPrimaryKey(instId, BompAppParamConstant.MCHNT_PARAM_TYPE, BompAppParamConstant.DEFAULT_D0_FEE);
                if (null == sysParam) {
                    rglog.error("根据机构号:<{}>,查询系统参数信息表机构默认提现费率信息失败!", instId);
                    throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                }

                queryBean.setBaseProdCode("*");
                queryBean.setFeeType(MchntFeeTypeEnum.DO.getType());
                queryBean.setFeeEffectiveDate(DateUtil.getCurrentDate());
                queryBean.setFeeExpiryDate(BompAppParamConstant.DEFAULT_EXPIRY_DATE);
                queryBean.setFeeRate(sysParam.getParamValue());
            } else {
                BeanUtil.beanCopy(dbMchntFeeInfo, queryBean);
            }

            mchntWithdrawManageResponse.setCashWithdrawalFeeInfoBean(queryBean);
        }

        mchntWithdrawManageResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        mchntWithdrawManageResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntWithdrawManageResponse);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntWithdrawManageResponse mchntWithdrawManageResponse = (MchntWithdrawManageResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntWithdrawManageResponse);
    }


    private BizHistory initBizHistoryByCreate(BizTmp bizTmp, String bizData, String createTime) {
        BizHistory bizHistory = new BizHistory();
        BeanUtil.beanCopy(bizTmp, bizHistory);
        InitParamUtil.initBizHistoryData(bizHistory, bizData);
        bizHistory.setCreateTime(createTime);
        return bizHistory;
    }


    /**
     * 新增提交待审批 商户信息
     */
    private void createMchntCashFeeInfoDb(MchntBaseInfo mchntBaseInfo,
                                          MchntSignInfo mchntSignInfo,
                                          MchntFeeInfo mchntFeeInfo,
                                          List<BizTmp> bizTmpList) throws Exception {
        BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();


        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        try {

            //更新商户结算状态等
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            int dbResult = mchntBaseInfoMapper.updateMchntBaseInfoById(mchntBaseInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("提现费率管理：更新商户基本信息表失败！id:{},mchnt:{},instId:{}",
                        mchntBaseInfo.getId(), mchntBaseInfo.getMchntNo(), mchntBaseInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            //修改签约信息 -> 修改待审核
            MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
            dbResult = mchntSignInfoMapper.updateMchntSignInfoById(mchntSignInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("提现费率管理：更新商户签约信息表失败！id:{},mchnt:{},instId:{}",
                        mchntSignInfo.getId(), mchntSignInfo.getMchntNo(), mchntSignInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }


            MchntFeeInfoMapper mchntFeeInfoMapper = new MchntFeeInfoMapperImpl();
            dbResult = mchntFeeInfoMapper.insertMchntFeeInfo(mchntFeeInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("提现费率管理：更新费率信息表失败！id:{},mchnt:{},instId:{}",
                        mchntFeeInfo.getId(), mchntFeeInfo.getMchntNo(), mchntFeeInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            if (!CollectionUtils.isEmpty(bizTmpList)) {
                for (BizTmp bizTmp : bizTmpList) {
                    //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
                    BizTmp oldBizTemp = bizTmpMapper.selectBizTmpByRealId(bizTmp.getInstId(), bizTmp.getRealId());
                    if (null == oldBizTemp) {
                        dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                    } else {
                        dbResult = bizTmpMapper.updateBizTmpByRealId(bizTmp);
                    }

                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("提现费率管理-临时表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizTmp.getRealId(), bizTmp.getManageInstId(), bizTmp.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("提现费率管理数据库操作失败！mchntNo:{}", mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 新增提交待审批 商户信息
     */
    private void modifyMchntCashFeeInfoDb(MchntBaseInfo mchntBaseInfo,
                                          MchntSignInfo mchntSignInfo,
                                          List<MchntFeeInfo> mchntFeeInfoList,
                                          List<BizTmp> bizTmpList) throws Exception {
        BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();


        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        try {

            //更新商户结算状态等
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            int dbResult = mchntBaseInfoMapper.updateMchntBaseInfoById(mchntBaseInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("提现费率管理：更新商户基本信息表失败！id:{},mchnt:{},instId:{}",
                        mchntBaseInfo.getId(), mchntBaseInfo.getMchntNo(), mchntBaseInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            //修改签约信息 -> 修改待审核
            MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
            dbResult = mchntSignInfoMapper.updateMchntSignInfoById(mchntSignInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("提现费率管理：更新商户签约信息表失败！id:{},mchnt:{},instId:{}",
                        mchntSignInfo.getId(), mchntSignInfo.getMchntNo(), mchntSignInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            MchntFeeInfoMapper mchntFeeInfoMapper = new MchntFeeInfoMapperImpl();
            if (!CollectionUtils.isEmpty(mchntFeeInfoList)) {
                for (MchntFeeInfo dbMchntFeeInfo : mchntFeeInfoList) {
                    dbResult = mchntFeeInfoMapper.updateMchntFeeInfoById(dbMchntFeeInfo);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("提现费率管理：更新商户费率信息表失败！id:{},mchnt:{},instId:{}",
                                dbMchntFeeInfo.getId(), dbMchntFeeInfo.getMchntNo(), dbMchntFeeInfo.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            if (!CollectionUtils.isEmpty(bizTmpList)) {
                for (BizTmp bizTmp : bizTmpList) {
                    //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
                    BizTmp oldBizTemp = bizTmpMapper.selectBizTmpByRealId(bizTmp.getInstId(), bizTmp.getRealId());
                    if (null == oldBizTemp) {
                        dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                    } else {
                        dbResult = bizTmpMapper.updateBizTmpByRealId(bizTmp);
                    }

                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("提现费率管理-临时表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizTmp.getRealId(), bizTmp.getManageInstId(), bizTmp.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("提现费率管理数据库操作失败！mchntNo:{}", mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }


    private BizTmp initBizTmpByCreate(MchntBaseInfo mchntBaseInfo,
                                      String id,
                                      String jsonString,
                                      String tableName,
                                      String auditStatus,
                                      String masterShowFlag,
                                      String detailFlag) {
        BizTmp bizTmp = new BizTmp();
        try {
            ConvertUtil.convertOutput(bizTmp);
        } catch (Exception e) {
            rglog.error("ConvertUtil异常：{}", e.toString());
        } finally {
            BeanUtil.beanCopy(mchntBaseInfo, bizTmp);
            bizTmp.setManageInstId(mchntBaseInfo.getSignInstId());
            bizTmp.setMchntName(mchntBaseInfo.getMchntName());
            bizTmp.setRealId(id);
            bizTmp.setOprTableEname(tableName);
            //状态非正式
            bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
            //新增
            bizTmp.setBizOpr("I");
            bizTmp.setAuditStatus(auditStatus);
            //主记录标识
            bizTmp.setDetailFlag(detailFlag);
            bizTmp.setMasterShowFlag(masterShowFlag);
            bizTmp.setMasterKey(mchntBaseInfo.getId());
            InitParamUtil.initBizTempData(bizTmp, jsonString);
        }
        return bizTmp;
    }
}
